#!/bin/bash

DUTCLOCATION=http://maia.usno.navy.mil/ser7/tai-utc.dat
IERSALOCATION=http://maia.usno.navy.mil/ser7/ser7.dat

# Get the DUTC table.
DUTCNAME=`basename $DUTCLOCATION`
#echo $DUTCNAME
rm -f $DUTCNAME $DUTCNAME.mod
wget $DUTCLOCATION
# We want a list of MJD versus DUTC.
cat $DUTCNAME | awk '{mjd = $5 - 2400000.5; print mjd,$7}' > $DUTCNAME.mod
declare -a MJD
declare -a DUTC
i=0
while read -ra line
do
    #echo ${line[0]}
    MJD[$i]=${line[0]}
    du=`echo ${line[1]} | sed -e 's/.[0-9]$//'`
    DUTC[$i]=$du
    i=$((i+1))
done < $DUTCNAME.mod

tLen=${#MJD[@]}

# We want to get the list of MJD vs IERS parameters.
IERSNAME=`basename $IERSALOCATION`
#echo $IERSNAME
rm -f $IERSNAME $IERSNAME.1 $IERSNAME.mod
wget $IERSALOCATION
awk '/^[[:blank:]]+2/ { print $4,$5,$6,$7 }' $IERSNAME > $IERSNAME.1
j=0
maxlines=100
while read -ra line
do
    if [ "$j" -lt "$maxlines" ]
    then
	imjd=${line[0]}
	tdutc=0
	for (( i=0; i<${tLen}; i++ ));
	do
	    if [ "${MJD[$i]}" -le "$imjd" ]
	    then
		tdutc=${DUTC[$i]}
	    fi
	done
	echo ${line[@]} $tdutc >> $IERSNAME.mod
    fi
    j=$((j+1))
done < $IERSNAME.1

# Clean up.
rm -f $IERSNAME $IERSNAME.1 $DUTCNAME $DUTCNAME.mod

